import { _decorator, Component, Prefab } from 'cc';
import { State, WSConnectedEvent, WSRecvDataEvent } from '../../../../Framework/Scripts/Managers/Net/NetCfg';
import { CocosUtils } from '../../../../Framework/Scripts/Utils/CocosUtils';
import { AbNames, EventMsgKes } from '../../Config/ResConfig';
import { GameData } from '../../Data/GameData';
import { IAnswerTimeOutReq, IBroadCorrectAnswerZt, IBroadCurEndZt, IBroadNextTopicZt, IDwGameEnd, IGetDwRewardReq, IGetDwRewardRes, IGetNextGroupReq, IGetNextGroupRes, IGetRecoreReq, IGetRecoreRes, IThemeMatchPPBroad, IThemeMatchStarBroad, IThemeMatchStarReq, IThemeMatchStarRes, IUserAnswerZtReq, IUserAnswerZtRes, IUserEnterZtReq, IUserEnterZtRes, IUserExitZtReq, IUserExitZtRes, IZTScene } from '../proto/gameZt';
import { UIMgr, UIType } from '../../../../Framework/Scripts/Managers/UIMgr';
import { GamePPSuccess_Ctr } from './GamePPSuccess_Ctr';
import { GamePlayZt_Ctr } from './GamePlayZt_Ctr';
import { ViewMgr } from '../../../../Framework/Scripts/Managers/ViewMgr';
import { ICall, SceneMgr } from '../../../../Framework/Scripts/Managers/SceneMgr';
import { GameDwEndZt_Ctr } from './GameDwEndZt_Ctr';
import { GameDwEndZtGet_Ctr } from './GameDwEndZtGet_Ctr';
const { ccclass, property } = _decorator;

var CmdZt = {
    ThemeMatchUserEnter:9200,//用户进入
    ThemeMatchGameBroad: 9201, //广播场景配置
    ThemeMatchStarReq:9202, //用户准备
    ThemeMatchGameSceneBroad: 9203,//两个用户准备完毕广播游戏场景
    ThemeMatchGameAnswerReq:9204, //用户答题
    GameAnswerEndBroadcast:9205, //广播正确答案
    ThemeMatchGameNextBroadcast:9206, //广播下一题
    ThemeMatchGameEndBroadcast:9207, //广播结算
    ThemeMatchGameLvUpEndBroadcast: 9208, //段位结算
    ThemeMatchGameNextGroupRes:9209, //下一组
    ThemeMatchGameRecordReq:9210, //当前记录
    ThemeMatchGetDwReward: 9211,    //领取段位奖励
    ThemeMatchAnswerTimeOut: 9212,    //用户答题超时
    ThemeMatchExit: 9213,    //用户退出
}
//主题赛消息
@ccclass('GameZtMsg')
export class GameZtMsg extends Component {
    net: any;
    url: string;
    start() {
        // this.InitUI();
        // this.InitData();

    }

    update(deltaTime: number) {
        if(this.net.state === State.Invalid) {
            return;
        }
        if(this.net.state === State.Disconnected) {
            console.log('=====游戏服务tz重新连接==========')
            this.net.connectServer( this.url);
        }
    }

    protected onDestroy(): void {
        this.unRegisterEvent();
    }

    
    public ConnectGameZt(ip,port){
        console.log('======开始链接游戏服务=======',ip.port);
        this.InitUI();
        this.InitData();

        this.url = CocosUtils.getUrlByIdAndPort(ip,port);
      
        this.net = new globalThis.gameMgr.WsMgr();
        this.net.connectServer(this.url);
    }

    private InitUI(){
        this.registerEvent();       
    }

    private InitData(){
        console.log('======_GameZtMsg=InitData=========',globalThis.gameMgr._GameZtMsg);
        globalThis.gameMgr._GameZtMsg = this;
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(WSConnectedEvent,this.onConnectGameServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevGameData,this);
    }

    private unRegisterEvent(){
        globalThis.gameMgr._eventTarget.off(WSConnectedEvent,this.onConnectGameServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevGameData,this);
    }

   //发送JSON数据
   private _sendJson(type: number, data: any){
        console.log('=======_sendJson======',type,data);
        this.net.sendJsonData(type,data);
    }

    //大厅服务网络连接成功
    private onConnectGameServer(data){
        console.log('=======onConnectGameServer zt===========');

        //移除加载的loading
        let parent1 = UIMgr.inst.getParent(UIType.UnFull);
        parent1.removeAllChildren();


        //打开游戏界面
        // UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameZT/GamePPSuccess',UIType.Full);
        // let pre = ResManager.inst.getAsset(AbNames.GamePlay,"Prefabs/GamePlay/GamePlayZt",Prefab) as Prefab;
        // let parent = UIMgr.inst.getParent(UIType.Full);
        // let node = instantiate(pre);
        // parent.addChild(node);
        // node.addComponent(GamePlayZt);

        //发送用户登录
        this.sendUserEnterReq();
    }

    private _onThemeMatchPPBroad(data:IThemeMatchPPBroad){
        console.log('=======_onThemeMatchPPBroad=========',data);
        let ts_node = UIMgr.inst.ShowUIView(AbNames.GameHall,'Prefabs/GameZT/GamePPSuccess', UIType.Full);
        // ts_node.setData(data.userList);
        // globalThis.gameMgr.zts_roomId = data.roomId;
    }


    /**
      * 主题赛---用户进入
      * @param dwType 玩法类型 文体 足球 民族
      */
    public sendUserEnterReq() {
        let req: IUserEnterZtReq = {
            userId: GameData.inst.userInfo.userId,
            type: globalThis.gameMgr.zts_type
        }
        console.warn('=========sendUserEnterReq=========',req);
        this._sendJson(CmdZt.ThemeMatchUserEnter, req);
    }
    
    //用户准备
    public ThemeMatchStarReq(){
        let req: IThemeMatchStarReq = {
            userId: GameData.inst.userInfo.userId,
            type: globalThis.gameMgr.zts_type,
        }
        console.log('======ThemeMatchStarReq=======',req);
        this._sendJson(CmdZt.ThemeMatchStarReq, req);
    }
    
    /**
     * 用户答题请求
     * @param tid 
     * @param cid 
     * @param costTime 花费的时间 
     * @param gameType 主题类型 文体1 足球2 民族3
     */
    public sendUserAnswerReq(tid: number, cid: number, costTime: number) {
        let req: IUserAnswerZtReq = {
            userId: GameData.inst.userInfo.userId,
            topicId: tid,
            choiceId: cid,
            costTime: costTime,
            gameType: globalThis.gameMgr.zts_type
        }
        console.log('=========sendUserAnswerReq=========',req);
        this._sendJson(CmdZt.ThemeMatchGameAnswerReq, req);
    }

    //请求答题回顾记录
    public sendGetRecord(){
        let req:IGetRecoreReq ={
            userId: GameData.inst.userInfo.userId,
        }
        this._sendJson(CmdZt.ThemeMatchGameRecordReq, req);
    }

    //主题赛当前组结束，请求下一组
    public sendNextGroupRes() {
        let req: IGetNextGroupReq ={
            userId: GameData.inst.userInfo.userId,
            gameType: globalThis.gameMgr.zts_type
        }
        this._sendJson(CmdZt.ThemeMatchGameNextGroupRes, req);
    }
    
    //领取段位奖励
    public sendGetDwReward(beishu: number){
        let req: IGetDwRewardReq ={
            userId: GameData.inst.userInfo.userId,
            bei: beishu
        }
        console.log('======sendGetDwReward=======',req);
        this._sendJson(CmdZt.ThemeMatchGetDwReward, req);
    }

    //用户答题超时
    public sendTimeOutAnswer(_tid: number){
        let req:IAnswerTimeOutReq = {
            userId: GameData.inst.userInfo.userId,
            tid: _tid
        }
        console.log('======sendTimeOutAnswer=======',req);
        this._sendJson(CmdZt.ThemeMatchAnswerTimeOut, req);
    }

    //用户退出
    public sendUserExit(){
        let req:IUserExitZtReq = {
            userId: GameData.inst.userInfo.userId,
        }
        console.log('======sendUserExit=======',req);
        this._sendJson(CmdZt.ThemeMatchExit, req);
    }

    //收到大厅服务数据
    private onRevGameData(binaryData){
        let msg = JSON.parse(binaryData);
        let ctype = msg.type;
        let data = msg.data;
        this._onMsg(ctype,data);
    }


    private _onMsg(ctype: number, msg: any) {
        console.log('=====GameZtMsg==_onMsg========',ctype);

        switch (ctype) {
            case CmdZt.ThemeMatchUserEnter: //用户进入
                this.onThemeMatchUserEnter(msg)
                break;
            case CmdZt.ThemeMatchGameBroad: //广播用户场景
                this.onThemeMatchGameBroad(msg);
                break;    
            case CmdZt.ThemeMatchStarReq://用户准备
                this.onThemeMatchStarReq(msg);
                break;    
            case CmdZt.ThemeMatchGameSceneBroad: //两个用户准备完毕广播游戏场景
                this.onThemeMatchGameSceneBroad(msg);
                break;    
            case CmdZt.ThemeMatchGameAnswerReq: //用户答题
                this.onThemeMatchGameAnswerReq(msg);
                break;
            case CmdZt.GameAnswerEndBroadcast:
                this.onGameAnswerEndBroadcast(msg); //广播正确答案
                break; 
            case CmdZt.ThemeMatchGameNextBroadcast: //广播下一题
                this.onThemeMatchGameNextBroadcast(msg);
                break;
            case CmdZt.ThemeMatchGameEndBroadcast: //广播结算
                this.onThemeMatchGameEndBroadcast(msg);
                break;  
            case CmdZt.ThemeMatchGameLvUpEndBroadcast://广播段位结算
                this.onThemeMatchGameLvUpEndBroadcast(msg);
                break;
            case CmdZt.ThemeMatchGameNextGroupRes: //下一组
                this.onThemeMatchGameNextGroupRes(msg);
                break;    
            case CmdZt.ThemeMatchGameRecordReq: //当前记录
                this.onThemeMatchGameRecordReq(msg);
                break;    
            case CmdZt.ThemeMatchGetDwReward: //领取段位奖励
                this.onThemeMatchGetDwReward(msg);
                break;    
            case CmdZt.ThemeMatchExit: //用户退出
                this.onThemeMatchExit(msg);
                    break;
            default:
                break;
        }
    }

    //用户进入
    private onThemeMatchUserEnter(data:IUserEnterZtRes){
        console.warn('=======onThemeMatchUserEnter=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchUserEnter, data);
    }

    //用户信息广播
    private onThemeMatchGameBroad(data:IThemeMatchPPBroad){
        console.warn('=======onThemeMatchGameBroad=======',data);

        //打开游戏界面
        let com= UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameZT/GamePPSuccess',UIType.Full) as GamePPSuccess_Ctr;
        com.setData(data.userList);

        globalThis.gameMgr.zts_roomId = data.roomId;
    }

    // 用户准备
    private onThemeMatchStarReq(data: IThemeMatchStarRes){
        console.warn('=======onThemeMatchStarReq=======',data);
    }

    // 两个用户准备完毕广播游戏场景
    private onThemeMatchGameSceneBroad(data:IThemeMatchStarBroad){
        console.warn('=======onThemeMatchGameSceneBroad=======',data);
        let com= UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameZT/GamePlayZt',UIType.Full) as GamePlayZt_Ctr;
        com.onThemeMatchGameRes(data);

        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGameRes, data);
    }

    // 用户答题
    private onThemeMatchGameAnswerReq(data:IUserAnswerZtRes){
        console.warn('=======onThemeMatchGameAnswerReq=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGameAnswerBroadcast, data);
    }

    //广播正确答案
    private onGameAnswerEndBroadcast(data:IBroadCorrectAnswerZt){
        console.warn('=======onGameAnswerEndBroadcast=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGameAnswerEndBroadcast, data);
    }

    // 广播下一题
    private onThemeMatchGameNextBroadcast(data:IBroadNextTopicZt){
        console.warn('=======onThemeMatchGameNextBroadcast=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGameNextBroadcast, data);
    }

    // 广播结算
    private onThemeMatchGameEndBroadcast(data:IBroadCurEndZt){
        console.warn('=======onThemeMatchGameEndBroadcast=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGameEndBroadcast, data);
    }

    // 广播段位结算
    private onThemeMatchGameLvUpEndBroadcast(data:IDwGameEnd){
        console.warn('=======onThemeMatchGameLvUpEndBroadcast=======',data);
        //段位结算弹窗
        let com = UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameZT/GameDwEndZt',UIType.Default) as GameDwEndZt_Ctr;
        com.setData(data);
    }

    // 下一组
    private onThemeMatchGameNextGroupRes(data:IGetNextGroupRes){
        console.warn('=======onThemeMatchGameNextGroupRes=======',data);
        //链接大厅服务，显示匹配页
        const callFunction = SceneMgr.inst.SetCallFun(SceneMgr.inst.showHallViwe);
        let call ={
            func: callFunction,
            path: "Prefabs/GameStart1/GameStart1"
        }
        ViewMgr.inst.ConnectToHall(call);

        //移除结算界面
        let parent = UIMgr.inst.getParent(UIType.UnFull);
        parent.removeAllChildren();
    }


    // 当前轮记录
    private onThemeMatchGameRecordReq(data:IGetRecoreRes){
        console.warn('=======onThemeMatchGameRecordReq=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGameRecordRes, data);
    }

    // 领取段位奖励
    private onThemeMatchGetDwReward(data:IGetDwRewardRes){
        console.warn('=======onThemeMatchGetDwReward=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchGetDwReward, data);
    }

    //用户退出游戏
    private onThemeMatchExit(data:IUserExitZtRes){
        console.warn('=======onThemeMatchExit=======',data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchExit, data);
    }
    
}


